require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class CostManager
CostManager = {};
local this = CostManager;

this._FLASHGIFTID = 20001;
this._GUILDGIFTID = 10217;
this._FIRSTPAYGIFTID = 30001;
this._PRIVILEGE = 40001;
this._ACCUMULATEPAYID=11004
this._FASTCONSUMPTION = 10215; --快捷购买
local activeTableData;
local tagTableData;
local serverTableData;
local stageConfig;
local vipTableData;
local itemLimitTableData;
local payDataTable;

local tagData = {};
--local activeOpenData = {};
--local transData = {};
--local activeEndQueue = {};
--local tagRedDots = {};
--local beginCountDownId = {};
--local endCountDownId = {};
--local endCountDownId = {};
--local endTimevVariableActive = {};
--local marketSubParams = {};
--local vipRewardList = {};
--local marketParams = {};
local conditionParams = {};
local lastSeverData;
local localConditionTime = {};

local waitPopTips;
local isNeedShowPopUpTips = true;
--local isFristAcceptServerData = true;
local serverRebateType = nil;
local localVoucherReward = nil;
local voucherData = nil;

function CostManager.initData()
    this.activeBeginTime = {};
    this.entranceList = {};
    this.activeEndTime = {};
    this.activeServerDataList = {};
    this.activeCircleEndTime = {};
    this.configKeys = { "f_NeedRencencyLevel", "f_UnlockStage", "f_UnlockTime", "f_UnlockVipRank"}

end

function CostManager.init()
    activeTableData = G.dataTable["t_storeentrance"];
    serverTableData = G.dataTable["t_storelist"];
    tagTableData = G.dataTable["t_storeicon"];
    stageConfig = G.dataTable["t_stage"];
    vipTableData = G.dataTable["t_vip"];
    itemLimitTableData = G.dataTable["t_itemlimit"];
    payDataTable = G.dataTable["t_pay"];
    waitPopTips = {};
    this.initData();
    --ListenEvent(Config.EventType.Fresh_Level, this.FreshLevelInfo);
end

function CostManager.OnDestroy()
    for _, v in pairs(this.activeBeginTime) do
        utimer.remove(v);
    end
    for _, v in pairs(this.activeEndTime) do
        utimer.remove(v);
    end
    for _, v in pairs(this.activeCircleEndTime) do
        utimer.remove(v);
    end
end

--处理市场数据
function CostManager.resCostData(data, clear)
    --this.updateServerData(data, clear);
end

--处理接收的活动数据
function CostManager.resCostServerData(data)
    for k, v in pairs(data) do
        v.marketId = v.marketId
        v.startTime = tonumber(tostring(v.startTime)) * 0.001;
        v.endTime = tonumber(tostring(v.endTime)) * 0.001;
        v.drawEndTime = v.endTime;
        v.marketData = v.marketData and decodeJsonStrToTabel( v.marketData ) or {}
    end
    -- local item = {}
    -- item.marketId = 10901
    -- item.startTime = 1626246489.954
    -- item.endTime = 1627456089.954
    -- item.drawEndTime = 1627456089.954
    -- item.marketData = {}
    -- table.insert(data, item)
    this.initAllActive(data);
end

--处理接收的单个数据
function CostManager.UpdateOneCostServerData(v)
    v.marketId = v.marketId
    v.startTime = tonumber(tostring(v.startTime)) * 0.001;
    v.endTime = tonumber(tostring(v.endTime)) * 0.001;
    v.drawEndTime = v.endTime;
    v.marketData = decodeJsonStrToTabel(v.marketData or {});
    lastSeverData = true;
    this.initAllActive({v});
end

function CostManager.initAllActive(data)
    if data == nil then
        return ;
    end
    local time = HelperFunc.GetServerTime();
    for k, v in pairs(data) do
        this.activeServerDataList[tostring(v.marketId)] = v;
        if time >= v.startTime then
            this.initOneActive(v.marketId);
        else
            this.removeOneActive(v.marketId);
            if this.activeBeginTime[v.marketId] ~= nil then
                utimer.remove(this.activeBeginTime[v.marketId]);
            end
            this.activeBeginTime[v.marketId] = utimer.timeCall(function()
                lastSeverData = true;
                this.initOneActive(v.marketId);
                this.refreshActive(0);
            end, (v.startTime - time) * 1000, 1);
        end
    end
    this.refreshActive(0);
    this.addPrivilegeBuff();
end

function CostManager.updateNotOpenActive()
    this.notOpenActive = this.notOpenActive or {};
    local data = {};
    for i = #this.notOpenActive, 1, -1 do
        if this.isOpenItem(this.getCostTableDataById(this.notOpenActive[i])) then
            table.insert(data, this.notOpenActive[i]);
            table.remove(this.notOpenActive, i);
        end
    end
    for k, v in pairs(data) do
        this.initOneActive(v);
    end
    if #data > 0 then
        this.refreshActive(3);
    end
end
function CostManager.initOneActive(id)
    local activeTable = this.getCostTableDataById(id);
    local activeServerTable = this.getCostServerTableDataById(id);
    local serverData = this.getActiveServerDataList(id);
    if id == nil or activeTable == nil or serverData == nil or activeTable.f_MenuClass == 0 then
        return ;
    end
    if not this.isOpenItem(activeTable) then
        this.notOpenActive = this.notOpenActive or {};
        table.insert(this.notOpenActive, id);
        return;
    end
    local time = HelperFunc.GetServerTime();
    if serverData.drawEndTime > time or serverData.drawEndTime < 0 then
        if this.activeEndTime[id] ~= nil then
            utimer.remove(this.activeEndTime[id]);
        end
        if serverData.drawEndTime > 0 then
            this.activeEndTime[id] = utimer.timeCall(function()
                this.removeOneActive(id);
            end, (serverData.drawEndTime - time) * 1000, 1);
        end

        local fristIndex = 0;
        for i = 1, #tagData do
            if tagData[i].fristId == activeTable.f_FirstClassBtn then
                fristIndex = i;
                break;
            end
        end
        if fristIndex == 0 then
            local _order = this.getCostTagTableDataById(activeTable.f_FirstClassBtn).f_Order or 999; 
            table.insert(tagData, {fristId=activeTable.f_FirstClassBtn, secondIds = {}, order = _order});
            fristIndex = #tagData
        end
        local secondIds = tagData[fristIndex].secondIds;
        local secondIndex = 0;
        for i = 1, #secondIds do
            if secondIds[i].secondId == activeTable.f_SecondClassBtn then
                secondIndex = i;
                break;
            end
        end
 
        if secondIndex == 0 then
            local _order = this.getCostTagTableDataById(activeTable.f_SecondClassBtn).f_Order or 999;
            table.insert(secondIds, {secondId=activeTable.f_SecondClassBtn, id = id, order = _order});
            table.sort(secondIds, function (a, b) return a.order < b.order; end);
        end
        table.sort(tagData, function (a, b) return a.order < b.order; end);
        if activeTable.f_LoginPop ~= "" then
            this.addPopUpTips(activeTable.f_LoginPop, id);
        end
        if activeServerTable.f_IsCircle == 2 and serverData.marketData.nextResetTime ~= nil and serverData.marketData.nextResetTime >= time * 1000 then
            if this.activeCircleEndTime[id] ~= nil then
                utimer.remove(this.activeCircleEndTime[id]);
            end
            this.activeCircleEndTime[id] = utimer.timeCall(function()
                costHandler.reqGetOneMarketInfo(id);
            end, tonumber(tostring(serverData.marketData.nextResetTime)) - time * 1000 + 5000, 1);
        end
    else
        this.removeOneActive(id);
    end
end

function CostManager.removeOneActive(id)
    -- local flag;
    for key, value in pairs(tagData) do
        for k, v in pairs(value.secondIds) do
            if v.id == id then
                local data = this.getCostServerTableDataById(id);
                if data.f_IsCircle == 1 then
                    costHandler.reqGetOneMarketInfo(id);
                else
                    table.remove(value.secondIds, k);
                    if next(value.secondIds) == nil then
                        table.remove(tagData, key);
                    end
                end
                -- flag = true;
                -- break ;
                FireEvent(Config.EventType.UICostUpdate, 2)
                return
            end
            -- if flag then
            --     break;
            -- end
        end
    end
    -- if flag then
    --     FireEvent(Config.EventType.UICostUpdate);
    -- end
end

---- 处理服务端数据
--function CostManager.updateServerData(data, needClear)
--    if data == nil then
--        return
--    end
--    if needClear then
--        activeOpenData = {};
--        tagData = {};
--        tagRedDots = {};
--        endTimevVariableActive = {};
--        for k, v in pairs(beginCountDownId) do
--            utimer.remove(v);
--        end
--        for k, v in pairs(endCountDownId) do
--            utimer.remove(v);
--        end
--    end
--    for k, v in pairs(data) do
--        local activeTable = activeTableData[tostring(v.marketID)];
--        local serverTable = serverTableData[tostring(v.marketID)];
--        local startTime = v.startTime;
--        activeOpenData[v.marketID] = v;
--        local time = HelperFunc.GetServerTime();
--        local startFlag = true;
--        tagRedDots[activeTable.f_SecondClassBtn] = nil;
--        -----------定时器-----
--        if serverTable ~= nil and activeTable ~= nil and startFlag then
--            if activeTable.f_MenuClass == 0 then
--                startFlag = false;
--            end
--        end
--        if serverTable ~= nil and activeTable ~= nil and startFlag then
--            -- 未开始
--            if startTime - serverTable.f_PreHeatPeriod > time then
--                startFlag = false;
--                utimer.remove(beginCountDownId[v.marketID]);
--                beginCountDownId[v.marketID] = utimer.timeCall(function( ... )
--                    this.activeStart(v.marketID);
--                end, (startTime - serverTable.f_PreHeatPeriod - time) * 1000, 1);
--            else
--                v.endTime = 0;
--                local severdd = this.getCostData(v.marketID);
--                if activeTable.f_ShowType == 2 then
--                    for key, value in pairs(severdd) do
--                        if v.endTime < value.endTime then
--                            v.endTime = value.endTime;
--                        end
--                    end
--                    v.endTime = v.endTime;
--                    table.insert(endTimevVariableActive, v.marketID);
--                elseif next(severdd) ~= nil then
--                    v.endTime = startTime + serverTable.f_RewardPeriod;
--                    -- 永久开启
--                    if serverTable.f_RewardPeriod == 0 then
--                        v.endTime = -1;
--                    end
--                end
--                if v.endTime ~= -1 and v.endTime < time then
--                    -- 已结束
--                    startFlag = false;
--                elseif v.endTime ~= -1 then
--                    -- 未结束
--                    utimer.remove(endCountDownId[v.marketID]);
--                    endCountDownId[v.marketID] = utimer.timeCall(function( ... )
--                        this.activeEnd(v.marketID);
--                    end, (v.endTime - time) * 1000, 1);
--                    if activeTable.f_ShowType == 2 then
--                        this.removeActiveEndQueue(v.marketID);
--                    end
--                end
--            end
--        end
--        ----------定时器------结束-----
--        if activeTable ~= nil and activeTable ~= nil and startFlag then
--            local fristIndex = 0;
--            for i = 1, #tagData do
--                if tagData[i].fristId == activeTable.f_FirstClassBtn then
--                    fristIndex = i;
--                    break;
--                end
--            end
--            if fristIndex == 0 then
--                local _order = this.getCostTagTableDataById(activeTable.f_FirstClassBtn).f_Order or activeTable.f_FirstClassBtn;
--                table.insert(tagData, {fristId=activeTable.f_FirstClassBtn, secondIds = {}, order = _order});
--                fristIndex = #tagData
--            end
--            local secondIds = tagData[fristIndex].secondIds;
--            local secondIndex = 0;
--            for i = 1, #secondIds do
--                if secondIds[i].secondId == activeTable.f_SecondClassBtn then
--                    secondIndex = i;
--                    break;
--                end
--            end
--            if secondIndex == 0 then
--                table.insert(secondIds, {});
--                secondIndex = #secondIds;
--            end
--            local _order = this.getCostTagTableDataById(activeTable.f_SecondClassBtn).f_Order or activeTable.f_SecondClassBtn;
--            secondIds[secondIndex] = {secondId=activeTable.f_SecondClassBtn, id = v.marketID, order = _order};
--            if activeTable.f_LoginPop ~= "" then
--                this.addPopUpTips(activeTable.f_LoginPop, v.marketID);
--            end
--            -----红点
--            if activeTable.f_RedDotType == 1 then
--                if Util.GetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId.."_cost_id:"..v.marketID) ~= os.date("%Y-%m-%d", time) then
--                    tagRedDots[activeTable.f_SecondClassBtn] = true;
--                end
--            elseif activeTable.f_RedDotType == 2 then
--                local flag = nil;
--                local itemsData = this.getCostData(v.marketID);
--                if itemsData.subId ~= nil then
--                    itemsData = itemsData.items;
--                end
--                for key, value in pairs(itemsData) do
--                    if value.money == 0 and value.residue ~= nil and value.residue > 0 or value.receiveState == 1 then
--                        flag = true;
--                        break;
--                    end
--                end
--                tagRedDots[activeTable.f_SecondClassBtn] = flag;
--            end
--            ----------------红点---------结束-------------
--        end
--    end
--    table.sort(tagData, function (a, b) return a.order < b.order; end);
--    for k, v in pairs(tagData) do
--        table.sort(v.secondIds, function (a, b) return a.order < b.order; end);
--    end
--    this.refreshActive();
--end

-- 刷新数据
function CostManager.refreshActive(type)
    -- 限时礼包
    this.setFlashGiftData();
    this.setGuildGift();
    FireEvent(Config.EventType.UICostUpdate, type);
    FireEvent(Config.EventType.Fresh_CostRedDot);
    lastSeverData = nil;
end

---- 活动开始
--function CostManager.activeStart(id)
--    local data = {};
--    table.insert(data, this.getCostOpenInfoById(id));
--    this.updateServerData(data);
--end

---- 活动结束
--function CostManager.activeEnd(id)
--     if id == nil then
--        return;
--    end
--    table.insert(activeEndQueue, id);
--    if not isOpenUI(PanelNames.UICost) then
--        this.clearActive();
--    end
--    local severTableData = this.getCostServerTableDataById(id);
--    if severTableData.f_IsCircle == 1 then
--        marketSubParams[tostring(id)] = nil;
--        marketParams[tostring(id)] = nil;
--        logicMgr.CostOpenManager.updateCircleActive();
--    end
--end

---- 移除集市清除列表
--function CostManager.removeActiveEndQueue(id)
--     if id == nil then
--        return;
--    end
--    for k, v in pairs(activeEndQueue) do
--        if v == id then
--            table.remove(activeEndQueue, k);
--            break;
--        end
--    end
--end

-- 领取奖励
function CostManager.getRewardById(id, index, callBack, tb)
    local indexs = {};
    if type(index) ~= "table" then
        if index == nil then
            index = id;
        end
        table.insert(indexs, tonumber(index));
    else
        indexs = index;
    end
    this.getRewardId = id;
    this.getRewardIndex = index;
    this.getRewardCallBack = callBack;
    this.getRewardtb = tb;
    costHandler.reqGetFetchReward(tonumber(id), indexs);
end

--集市代币购买
function CostManager.getRewardByCurrency(id, index, callBack, tb)
    local indexs = {};
    if type(index) ~= "table" then
        if index == nil then
            index = id;
        end
        table.insert(indexs, tonumber(index));
    else
        indexs = index;
    end
    this.getRewardId = id;
    this.getRewardIndex = index;
    this.getRewardCallBack = callBack;
    this.getRewardtb = tb;
    costHandler.ReqCurrencyBuyReward(tonumber(id), indexs);
end

-- 购买商品
function CostManager.getRewardByIdAndIndex(id, index, payId, num, money, callBack, tb, beforeCallBack)
    --[[
    local indexs = {};
    if type(index) ~= "table" then
        table.insert(indexs, index);
    else
        indexs = index;
    end
    this.getRewardId = id;
    this.getRewardIndex = index;
    this.getRewardCallBack = callBack;
    this.getRewardBeforeCallBack = beforeCallBack;
    this.getRewardtb = tb;
    this.getMoney = money;
    --]]
    --costHandler.reqBuyCost(tonumber(id), indexs, payId, num, 1);
    this.BuyCostType(id, index, payId, num, 1, money, callBack, tb);
end

this.fastPayType = 0;  -- 0:普通支付  1:代金券  2:飞飞币
function CostManager.BuyCostType(id, index, payId, num, buyType, money, callBack, tb)
    local pay_config = G.dataTable["t_pay"][tostring(payId)];
    if pay_config == nil then
        logError("t_pay 找不到, payId "..tostring(payId));
        return
    end
    local couponNum = tonumber(logicMgr.ItemManager.getBagNumByTableID(tonumber(200028)));
    local costNum = tonumber(pay_config.f_Price);
    -- 判断是否可以使用飞飞币
    if pay_config ~= nil and tonumber(pay_config.f_Buy) == 1 then
        --需判断飞飞币
        local petNum = tonumber(logicMgr.ItemManager.getCurrencyCountByModelId(tonumber(35)));
        local petCostNum = tonumber(pay_config.f_PricePet);
        if costNum > 0 and ((couponNum > 0 and couponNum >= costNum) or (petNum > 0 and petNum >= petCostNum)) then
            if this.fastPayType == 0 then
                this.showCouponPop(id, index, payId, num, buyType, money, callBack, tb);
            elseif this.fastPayType == 1 then
                if couponNum > 0 and couponNum >= costNum then
                    this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 2);
                else
                    this.showCouponPop(id, index, payId, num, buyType, money, callBack, tb);
                end
            elseif this.fastPayType == 2 then
                if petNum > 0 and petNum >= petCostNum then
                    this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 3);
                else
                    this.showCouponPop(id, index, payId, num, buyType, money, callBack, tb);
                end
            else
                this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 1);
            end
        else
            this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 1);
        end
    else
        --判断是否有足够代金券
        if costNum > 0 and couponNum > 0 and couponNum >= costNum then
            if this.fastPayType ~= 1 then
                this.showCouponPop(id, index, payId, num, buyType, money, callBack, tb);
            else
                this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 2);
            end
        else
            this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 1);
        end
    end
end

function CostManager.showCouponPop(id, index, payId, num, buyType, money, callBack, tb)
    this.fastPayType = 0;
    showUI(PanelNames.UICouponPop, payId, function(payType)
        local localPayType = tonumber(payType);
        if localPayType == 1 then
            this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 2);
        elseif localPayType == 2 then
            this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 1);
        elseif localPayType == 3 then
            this.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, 3);
        end
    end);
end

--为什么不改上面接口,而是新写一个接口,是因为不知道多少处引用了,也懒得查
function CostManager.BuyCostMode(id, index, payId, num, buyType, money, callBack, tb, payType)
    local indexs = {};
    if type(index) ~= "table" then
        table.insert(indexs, index);
    else
        indexs = index;
    end
    local giftId = indexs[1];
    if tonumber(buyType) == 2 then
        this.getRewardId = nil;
        this.getRewardIndex = nil;
        this.getRewardCallBack = nil;
        this.getRewardtb = nil;
        this.getMoney = nil;
    else
        this.getRewardId = id;
        this.getRewardIndex = index;
        this.getRewardCallBack = callBack;
        this.getRewardtb = tb;
        this.getMoney = money;
    end
    local selectPayType = tonumber(payType);
    --print("selectPayType = "..selectPayType);
    if selectPayType == 2 then--代金券
        costHandler.ReqVoucherBuy(tonumber(id), indexs, payId, num, buyType, 1, giftId);
    elseif selectPayType == 3 then--飞飞币
        costHandler.ReqVoucherBuy(tonumber(id), indexs, payId, num, buyType, 2, giftId);
    else
        costHandler.reqBuyCost(tonumber(id), indexs, payId, num, buyType, giftId);
    end
end

function CostManager.setFastPayType(value)
    this.fastPayType = tonumber(value);
end

-- 选择商品
function CostManager.chooseItemByCostIdAndIndex(id, index, itemList, assistId)
    costHandler.reqCostChooseItem(id, index, itemList, assistId);
end

-- 领取奖励返回
function CostManager.getFetchReward(data)
    if this.getRewardBeforeCallBack then
        this.getRewardBeforeCallBack(this.getRewardtb, this.getRewardId, this.getRewardIndex);
    end
    logicMgr.HeroManager.showNewHero(function ()
        if data ~= nil then
            local rewards = {};
            local flag = false;
            for k,v in pairs(data) do
                local itemData = this.getItemOrEquipDataByIdAndNum(v.itemID, v.itemNum);
                if itemData ~= nil then
                    table.insert(rewards, itemData);
                end
                if v.itemID == 1 then
                    flag = true;
                end
            end
            if #rewards == 0 then
                this.closeItemGet();
            else
                showUI(PanelNames.UICommonItemGet, nil, nil, 3, rewards, this.closeItemGet, nil, flag);
            end
        end
    end);
end

--领取奖励返回 (难受)
function CostManager.getFetchRewardNew(data)
    if this.getRewardBeforeCallBack then
        this.getRewardBeforeCallBack(this.getRewardtb, this.getRewardId, this.getRewardIndex);
    end
    logicMgr.HeroManager.showNewHero(function ()
        if data ~= nil then
            local rewards = {};
            local flag = false;
            for k,v in pairs(data) do
                local itemData = this.getItemOrEquipDataByIdAndNum(v.itemModelId, v.num);
                if itemData ~= nil then
                    table.insert(rewards, itemData);
                end
                if v.itemID == 1 then
                    flag = true;
                end
            end
            if #rewards == 0 then
                this.closeItemGet();
            else
                showUI(PanelNames.UICommonItemGet, nil, nil, 3, rewards, this.closeItemGet, nil, flag);
            end
        end
    end);
end

function CostManager.getFetchRewardModelId(data)
    if this.getRewardBeforeCallBack then
        this.getRewardBeforeCallBack(this.getRewardtb, this.getRewardId, this.getRewardIndex);
    end
    logicMgr.HeroManager.showNewHero(function ()
        if data ~= nil then
            local rewards = {};
            local flag = false;
            for k,v in pairs(data) do
                local itemData = this.getItemOrEquipDataByIdAndNum(v.itemModelId, v.num);
                if itemData ~= nil then
                    table.insert(rewards, itemData);
                end
                if v.itemModelId == 1 then
                    flag = true;
                end
            end
            if #rewards == 0 then
                this.closeItemGet();
            else
                showUI(PanelNames.UICommonItemGet, nil, nil, 3, rewards, this.closeItemGet, nil, flag);
            end
        end
    end);
end

function CostManager.closeItemGet()
    logicMgr.FlashGiftManager.showNewFlashGift();
    if this.getRewardCallBack then
        this.getRewardCallBack(this.getRewardtb, this.getRewardId, this.getRewardIndex);
    end
    this.getRewardId = nil;
    this.getRewardIndex = nil;
    this.getRewardCallBack = nil;
    this.getRewardtb = nil;
    this.getMoney = nil;
end

--- 跳转
function CostManager.gotoCostById(id, fun)
    showUI(PanelNames.UICost, fun, id);
    --showUI(PanelNames.UICostEntrance);
end

function CostManager.setNeedShowCsotId(id)
    if id ~= nil then
        id = tonumber(id);
    end
    this.needShowCostId = id;
end

function CostManager.getNeedShowCsotId()
    if this.needShowCostId == 0 or this.needShowCostId == nil then
        this.needShowCostId = nil;
        local data = G.dataTable["t_global"][tostring(177)].f_string_value;
        if data ~= nil then
            data = decodeJsonStrToTabel(data);
            for k, v in pairs(data) do
                for k1, v1 in pairs(tagData) do
                    for key, value in pairs(v1.secondIds) do
                        if value.id == v then
                            this.needShowCostId = v;
                            return this.needShowCostId;
                        end
                    end
                end
            end
        else
            this.needShowCostId = nil;
        end
    end
    return this.needShowCostId;
end

--- 获取一二级按钮ID
function CostManager.getFristIdAndSecondId()
    local id = this.getNeedShowCsotId();
    local fristId;
    local secondId;
    local flag = false;
    if id ~= nil then
        id = tonumber(id);
        for k, v in pairs(tagData) do
            for key, value in pairs(v.secondIds) do
                if value.id == id then
                    fristId = v.fristId;
                    secondId = value.secondId;
                    flag = true;
                    break;
                end
            end
            if flag then
                break;
            end
        end
    end
    if not flag then
        fristId = 1;
        secondId = 1;
        if #tagData > 0 then
            fristId = tagData[1].fristId;
            if #tagData[1].secondIds > 0 then
                secondId = tagData[1].secondIds[1].secondId;
            end
        end
    end
    return fristId, secondId;
end

-- 获取一二级按钮ID
function CostManager.getFristIdAndSecondIdByFristIndexAndSecondIndex(fristIndex, secondIndex, isSecond)
    if fristIndex == nil or secondIndex == nil then
        return 0, 0;
    end
    local isSecondTag = isSecond or false;
    local firstId = tonumber(tagData[fristIndex].fristId);
    if firstId == 10400 and secondIndex == 1 and not isSecondTag then
        local globalCfg = G.dataTable["t_global"][tostring(175)].f_string_value;
        if globalCfg ~= nil then
            globalCfg = decodeJsonStrToTabel(globalCfg);
            local secondIds = tagData[fristIndex].secondIds;
            for i = 1, #globalCfg do
                for k,v in pairs(secondIds) do
                    if tonumber(v.id) == tonumber(globalCfg[i]) then
                        return firstId, v.secondId, v.id;
                    end
                end
            end
            return tagData[fristIndex].fristId, tagData[fristIndex].secondIds[secondIndex].secondId, tagData[fristIndex].secondIds[secondIndex].id;
        else
            return tagData[fristIndex].fristId, tagData[fristIndex].secondIds[secondIndex].secondId, tagData[fristIndex].secondIds[secondIndex].id;
        end
    else
        return tagData[fristIndex].fristId, tagData[fristIndex].secondIds[secondIndex].secondId, tagData[fristIndex].secondIds[secondIndex].id;
    end
end

-- 获取一级页签信息
function CostManager.getFristClassData()
    return tagData or {};
end

-- 获取二级页签信息
function CostManager.getSecondClassDataByFristIndex(index)
    if index == nil then
        return {};
    end
    return tagData[index].secondIds or {};
end

-- 获取页签红点状态
function CostManager.getTagRedDotById(id)
    local serverData;
    for k , v in pairs(this.getFristClassData()) do
        if v.fristId == id or id == nil then
            for key, value in pairs(v.secondIds) do
                serverData = this.getCostData(value.id);
                if serverData.redDots then
                    return true;
                end
            end
        end
    end
    serverData = this.getCostData(id);
    if serverData and serverData.redDots then
        return true;
    end
    return false;
end

----- 更新子项可操作类页签红点状态
--function CostManager.updateActiveReceiveStatus(list, id, type)
--    if type == nil then
--        type = {};
--    end
--    local canReceive = nil;
--    for k, v in pairs(list) do
--        for key, value in pairs(type) do
--            if v.receiveState == value then
--                canReceive = true;
--                break;
--            end
--        end
--        if v.money == 0 and v.residue ~= nil and v.residue > 0 then
--            canReceive = true;
--        end
--        if canReceive then
--            break;
--        end
--    end
--    tagRedDots[id] = canReceive;
--    FireEvent(Config.EventType.Fresh_CostRedDot);
--end

-- 获取打开类页签红点状态
function CostManager.getActiveOpenStatus(id)
    local tableData = this.getCostTableDataById(id);
    if tableData.f_RedDotType == 1 then
        if GetPlayerPrefsAfter5AMFlag("redDotOne"..logicMgr.HeroManager.GetRoleInfo().playerId.."_cost_id:"..id) then
            return true;
        end
    elseif tableData.f_RedDotType == 2 then
        if Util.GetPlayerPrefs("redDotTwo"..logicMgr.HeroManager.GetRoleInfo().playerId.."_cost_id:"..id) == nil then
            return true;
        end
    end
    return nil;
end

-- 更新打开类页签红点状态
function CostManager.updateActiveOpenStatus(id)
    local tableData = this.getCostTableDataById(id);
    if tableData.f_RedDotType == 1 then
        if GetPlayerPrefsAfter5AMFlag("redDotOne"..logicMgr.HeroManager.GetRoleInfo().playerId.."_cost_id:"..id) then
            SetPlayerPrefsAfter5AMFlag("redDotOne"..logicMgr.HeroManager.GetRoleInfo().playerId.."_cost_id:"..id)
            FireEvent(Config.EventType.Fresh_CostRedDot);
        end
    elseif tableData.f_RedDotType == 2 then
        local key = "redDotTwo"..logicMgr.HeroManager.GetRoleInfo().playerId.."_cost_id:"..id;
        if Util.GetPlayerPrefs(key) == nil then
            Util.SetPlayerPrefs(key, "true");
            FireEvent(Config.EventType.Fresh_CostRedDot);
        end
    end
end

-- 获取活动信息
function CostManager.getCostDataByFristIndexAndSecondIndex(fristIndex, secondIndex)
    if fristIndex == nil or secondIndex == nil then
        return {};
    end
    if tagData[fristIndex] then
        return tagData[fristIndex].secondIds[secondIndex] or {};
    end
    return nil;
end

----- 获取活动服务器子项信息
--function CostManager.getCostServerDataById(id)
--    if id == nil then
--        return {};
--    end
--    return marketSubParams[tostring(id)] or {};
--end
--
----- 获取活动服务器活动信息
--function CostManager.getCostServerHeadDataById(id)
--    if id == nil then
--        return {};
--    end
--    return marketParams[tostring(id)] or {};
--end

--- 获取活动服务器活动信息
function CostManager.getActiveServerDataList(id)
    if id == nil then
        return this.activeServerDataList or {};
    end
    return this.activeServerDataList[tostring(id)];
end

--- 获取集市开启条件
function CostManager.getCostOpenServerConditionById(id)
    if id == nil then
        return {};
    end
    return conditionParams[tostring(id)] or {};
end

----- 获取集市开启信息
--function CostManager.getCostOpenInfoById(id)
--    if id == nil then
--        return {};
--    end
--    return activeOpenData[tonumber(id)] or {};
--end

-- 获取活动表格信息
function CostManager.getCostTableDataById(id)
    if id == nil then
        return {};
    end
    return activeTableData[tostring(id)] or {};
end

-- 获取服务器活动表格信息
function CostManager.getCostServerTableDataById(id)
    if id == nil then
        return {};
    end
    return serverTableData[tostring(id)] or {};
end

-- 获取活动页签按钮表格信息
function CostManager.getCostTagTableDataById(id)
    if id == nil then
        return {};
    end
    return tagTableData[tostring(id)] or {};
end

-- 获取活动页签按钮表格信息
function CostManager.clearId()
    this.setNeedShowCsotId();
    --this.clearActive();
end

---设置用户消费等级
function CostManager.setPlayerConsumeClass(data)
    this.playerConsumeClass = tonumber(data);
end

---用户消费等级
function CostManager.getPlayerConsumeClass()
    return this.playerConsumeClass or 1;
end

--- 设置用户充值数 (本来想要充值数的，后端只给了是否充值 0， 1), 唉，当首充用吧，不想改了
function CostManager.setPlayerRechargeNum(num)
    -- 防止以后给long
    this.playerRechargeNum = tonumber(tostring(num));
end

--- 用户充值数
function CostManager.getPlayerRechargeNum()
    return this.playerRechargeNum or 0;
end

--- 设置用户充值数,这个才是真正的充值数
function CostManager.setPlayerRechargeSum(num)
    if num == nil then
        this.playerRechargeSum = 0;
    else
        this.playerRechargeSum = tonumber(tostring(num));
    end
    if this.playerRechargeSum >= 6 then
        this.setPlayerRechargeNum(1);
    end
end

--
--function CostManager.clearActive()
--    local data = {};
--    if #activeEndQueue > 0 then
--        for i = 1, #activeEndQueue do
--            --activeOpenData[activeEndQueue[i]] = nil;
--            this.clearOneActive(activeEndQueue[i]);
--        end
--        activeEndQueue = {};
--        --for k, v in pairs(activeOpenData) do
--        --    table.insert(data, v);
--        --end
--        --table.sort(data, function(a, b) return a.marketID < b.marketID end);
--        --this.updateServerData(data, true);
--    end
--end

--function CostManager.clearOneActive(id)
--    local activeTable = activeTableData[tostring(id)];
--    for k, v in pairs(tagData) do
--        if v.fristId == activeTable.f_FirstClassBtn then
--            for key, value in pairs(v.secondIds) do
--                if value.secondId == activeTable.f_SecondClassBtn then
--                    table.remove(v.secondIds, key);
--                    break;
--                end
--            end
--            if #v.secondIds == 0 then
--                table.remove(tagData, k);
--            end
--            break;
--        end
--    end
--end

---获取活动数据
function CostManager.getCostData(id)
    if id == nil then
        return {}, {};
    end
    this.setOpenCondition();
    local activeTable = serverTableData[tostring(id)] or {};
    local type = tonumber(activeTable.f_StoreType);
    if type == 1 then
        return this.disposeMonthCardSeverData(id);
    elseif type == 2 then
        return this.disposeBornGiftSeverData(id);
    elseif type == 3 then
        return this.disposeDailyGiftSeverData(id);
    elseif type == 4 then
        return this.disposeOptionalGiftSeverData(id);
    elseif type == 5 then
        return {}, {};
    elseif type == 6 then
        return this.disposeFirstPayGiftData(id);
    elseif type == 7 then
        return this.disposeGiftGrowUpData(id);
    elseif type == 8 then
        return this.disposeBattlePassData(id);
    elseif type == 9 then
        return this.disposeGiftVip(id);
    elseif type == 10 then
        return this.disposePrivilege(id);
    elseif type == 11 then
        return this.disposeGiftDay(id);
    elseif type == 12 then
        return this.disposeGiftHero(id)
    elseif type == 13 then
        return this.disposeFastConsumption(id);
    elseif type == 14 then
        return this.disposeBattlePassData(id);
    elseif type == 15 then
        return this.disposeSevenRankPlusFastConsumption(id);
    else
        return {}, {};
    end
end

function CostManager.getCostInitialDataById(id)
    local serverData = CostManager.getActiveServerDataList(id);
    local curData = CostManager.getCostTableDataById(id);
    if curData ~= nil then
        local modelTableData = G.dataTable[curData.f_ModelName][tostring(id)];
        if modelTableData ~= nil then
            local tableData = G.dataTable[modelTableData.f_ItemTableName] or {};
            return serverData, tableData, modelTableData;
        else
            logError("找不到集市模板"..tostring(curData.f_ModelName).." f_StoreId:"..tostring(id));
            return nil;
        end
    else
        logError("找不到集市t_storeentrance f_StoreId:"..tostring(id));
        return nil;
    end
end

---处理限时礼包数据
function CostManager.setFlashGiftData()
    local data = this.getActiveServerDataList(this._FLASHGIFTID);
    if data == nil then
        --logError("[setFlashGiftData]data is nil")
        return
    end
    if lastSeverData ~= nil then
        logicMgr.FlashGiftManager.addFlashGiftByLastData(data.marketData.dataMap);
    else
        logicMgr.FlashGiftManager.resCostData(data.marketData.dataMap);
    end
end

function CostManager.setGuildGift()
    local data = this.getActiveServerDataList(this._GUILDGIFTID);
    if data then
        logicMgr.GuildManager.SetGuildGiftSrvData(data)
    end
end

---处理创角礼包数据
function CostManager.disposeBornGiftSeverData(id)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(id);
    if serverData == nil or tableData == nil then
        return {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.items = {};
    serveritems.redDots = this.getActiveOpenStatus(id);
    if serverData.marketData.buyCountMap == nil then
        serverData.marketData.buyCountMap = {};
    end
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == id then
            local buyCount = serverData.marketData.buyCountMap[tostring(v.f_ItemId)];
            if buyCount == nil then
                buyCount = 0;
            end
            local item = {};
            if buyCount < v.f_Count then
                item.subId = v.f_ItemId;
                item.buyCount = buyCount;
                item.money = v.f_Price;
                item.residue = v.f_Count - item.buyCount;
                item.order = v.f_Order;
                table.insert(serveritems.items, item);
                if item.residue > 0 and item.money == 0 then
                    serveritems.redDots = true;
                end
            end
        end
    end
    table.sort(serveritems.items, function (a, b) return a.order < b.order end);
    return serveritems, tableData, modelTableData;
end

---处理月卡数据
function CostManager.disposeMonthCardSeverData(id)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(id);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.items = {};
    serveritems.redDots = this.getActiveOpenStatus(id);
    if serverData.marketData.dataMap == nil then
        serverData.marketData.dataMap = {};
    end
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == id then
            local item = serverData.marketData.dataMap[tostring(v.f_MonthlyCardId)];
            if item == nil then
                item = {};
                item.subId = v.f_MonthlyCardId;
                item.remainDay = 0;
            end
            item.order = v.f_Order;
            table.insert(serveritems.items, item);
        end
    end
    table.sort(serveritems.items, function (a, b) return a.order < b.order end);
    return serveritems, tableData, modelTableData;
end

---处理日常礼包数据
function CostManager.disposeDailyGiftSeverData(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    if serverData.marketData.nextResetTime ~= nil then
        serveritems.nextRefreshTime = serverData.marketData.nextResetTime * 0.001;
    end
    serveritems.items = {};
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    if serverData.marketData.buyCountMap == nil then
        serverData.marketData.buyCountMap = {};
    end
    if serverData.marketData.buyCountSumMap == nil then
        serverData.marketData.buyCountSumMap = {};
    end
    local tableNum = 0;
    for k, v in pairs(tableData) do
        tableNum = tableNum + 1;
    end
    local _costItem = {};
    local _noCostItem = {};
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == activeId and v.f_BeforeConsumptionID == 0 and this.isOpenItem(v) then
            local item = serverData.marketData.buyCountMap[tostring(v.f_ItemId)];
            if item == nil then
                item = 0;
            end
            local costItem = v;
            local flag = 1;
            while item >= costItem.f_Count and costItem.f_NextConsumptionID ~= 0 do
                if costItem.f_Num ~= -1 then
                    local localServerItem = {};
                    local countSum = serverData.marketData.buyCountSumMap[tostring(costItem.f_ItemId)] or 0;
                    local cfgNum = costItem.f_Num;
                   if countSum < cfgNum then
                       localServerItem.money = costItem.f_Price;
                       localServerItem.countSum = cfgNum - countSum;
                    else
                       localServerItem.countSum = -10;
                       localServerItem.money = 0;
                    end
                    localServerItem.subId = costItem.f_ItemId;
                    localServerItem.buyCount = item;
                    localServerItem.order = costItem.f_Order;
                    localServerItem.residue = 1;
                    table.insert(_costItem, localServerItem);
                end
                if not this.isOpenItem(tableData[tostring(costItem.f_NextConsumptionID)]) then
                    break;
                end

                item = serverData.marketData.buyCountMap[tostring(costItem.f_NextConsumptionID)];
                costItem = tableData[tostring(costItem.f_NextConsumptionID)];
                if item == nil then
                    break;
                end
                flag = flag + 1;
                if flag > tableNum + 10 then
                    break;
                end
            end
            local serverItem = {};
            item = serverData.marketData.buyCountMap[tostring(costItem.f_ItemId)];
            local countSum = serverData.marketData.buyCountSumMap[tostring(costItem.f_ItemId)] or 0;
            local cfgNum = costItem.f_Num;
            if cfgNum == -1 then
                serverItem.money = costItem.f_Price;
                serverItem.countSum = cfgNum;
            elseif countSum < cfgNum then
                serverItem.money = costItem.f_Price;
                serverItem.countSum = cfgNum - countSum;
            else
                serverItem.countSum = -10;
                serverItem.money = 0;
            end
            serverItem.subId = costItem.f_ItemId;
            serverItem.buyCount = item or 0;
            serverItem.order = costItem.f_Order;
            serverItem.residue = costItem.f_Count - serverItem.buyCount;
            local isTempData = false;
            if cfgNum ~= -1 and serverItem.residue <= 0 then
                table.insert(_noCostItem, {serverItem.subId, serverItem.residue});
                serverItem.residue = 1;
                isTempData = true;
            end
            if serverItem.money == 0 and serverItem.residue > 0 and not isTempData then
                serveritems.redDots = true;
            end
            table.insert(serveritems.items, serverItem);
        end
    end
    for k, v in pairs(_costItem) do
        table.insert(serveritems.items, v);
    end
    table.sort(serveritems.items, function(a, b)
        if a.residue <= 0 and b.residue <= 0 or a.residue > 0 and b.residue > 0 then
            if a.money == 0 and b.money == 0 then
                return a.order < b.order;
            elseif a.money == 0 or b.money == 0 then
                return a.money < b.money;
            else
                return a.order < b.order;
            end
        else
            return a.residue > 0;
        end
    end)
    for k, v in pairs(_costItem) do
        for k1,v1 in pairs(serveritems.items) do
            if v.subId == v1.subId then
                v1.residue = 0;
            end
        end
    end
    for k, v in pairs(_noCostItem) do
        for k1,v1 in pairs(serveritems.items) do
            if v[1] == v1.subId then
                v1.residue = v[2];
            end
        end
    end
    return serveritems, tableData, modelTableData;
end

---处理自选礼包数据
function CostManager.disposeOptionalGiftSeverData(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.items = {};
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    if serverData.marketData.subDataMap == nil then
        serverData.marketData.subDataMap = {};
    end
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == activeId then
            local item = serverData.marketData.subDataMap[tostring(v.f_ItemId)];
            if item == nil then
                item = {};
                item.subId = v.f_ItemId;
                item.buyCount = 0;
                item.chooseItemIdList = {};
            end
            --if v.f_Count > item.buyCount then
                item.residue = v.f_Count - item.buyCount;
                item.order = v.f_Order;
                table.insert(serveritems.items, item);
                if v.f_Price == 0 and item.residue > 0 then
                    serveritems.redDots = true;
                end
            --end
        end
    end
    table.sort(serveritems.items, function (a, b)
        if a.residue <= 0 and b.residue <= 0 or a.residue > 0 and b.residue > 0 then
            return a.order < b.order;
        else
            return a.residue > 0;
        end
    end);
    return serveritems, tableData, modelTableData;
end

---处理首充礼包数据
function CostManager.disposeFirstPayGiftData(id)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(id);
    local serveritems = {};
    if serverData == nil then
        return {}, {};
    end
    modelTableData.f_Reward = decodeJsonStrToTabel(modelTableData.f_Reward)
    serveritems.startTime = serverData.startTime or 0;
    serveritems.endTime = serverData.endTime or 0;
    serveritems.drawEndTime = serverData.drawEndTime or 0;
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    serveritems.canShow = true;
    serveritems.receiveList = {};
    if serverData.startTime > HelperFunc.GetServerTime() then
        serveritems.receiveState = 4;
        serveritems.canShow = nil;
    elseif serverData.marketData.firstRechargeTime and serverData.marketData.firstRechargeTime > 0 then
        serveritems.receiveState = 2;
        local openTime = logicMgr.ActiveManager.getDataUpateTime(serverData.marketData.firstRechargeTime * 0.001);
        openTime = HelperFunc.GetServerTime() - openTime;
        for i = 1, #modelTableData.f_Reward do
            if openTime > 0 then
                if this.isExistInListByValue(serverData.marketData.receivedSet, i) then
                    serveritems.receiveList[i] = 2;
                else
                    serveritems.receiveState = 1;
                    serveritems.redDots = true;
                    serveritems.receiveList[i] = 1;
                end
            else
                if serveritems.receiveState == 2 then
                    serveritems.receiveState = 3;
                end
                serveritems.receiveList[i] = 0;
            end
            openTime = openTime - 24*60*60;
        end
        if serveritems.receiveState == 2 then
            serveritems.canShow = nil;
        end
    else
        serveritems.receiveState = 0;
    end
    return serveritems, tableData, modelTableData;
end

---处理成长基金礼包数据
function CostManager.disposeGiftGrowUpData(activeId)
    local itemTableData = G.dataTable["t_growthreward"];
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    serveritems.curLeftRewardNum = 0;
    local mapId = MapManager.getMapId();
    local current = stageConfig[tostring(mapId)];
    local nowCurrent ;
    if current.f_NextStage ~= nil and current.f_NextStage > 0 then
        nowCurrent = stageConfig[tostring(current.f_NextStage)].f_ChapterId - 1;
    else
        nowCurrent = current.f_ChapterId;
    end
    if serverData.marketData.subDataMap == nil then
        serverData.marketData.subDataMap = {};
    end
    if serverData.marketData.freeList==nil then
        serverData.marketData.freeList={}
    end
    local freeStates={}
    for i,v in pairs(serverData.marketData.freeList)do
        freeStates[v]=true
    end

    local tableNum = 0;
    for k, v in pairs(tableData) do
        tableNum = tableNum + 1;
    end
    local freeNum = #serverData.marketData.freeList;
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == activeId and v.f_BeforeId == 0 then
            local costItem = v;
            local item;
            local itemData;
            local flag = 1;
            while flag < tableNum + 10 do
                itemData = CostManager.findTableDataByBelong(itemTableData, costItem.f_ItemId);
                local itemDataNum = #itemData;
                item = serverData.marketData.subDataMap[tostring(costItem.f_ItemId)];
                if item == nil or item.buyCount == 0 then
                    item = {};
                    item.subId = costItem.f_ItemId;
                    item.buyCount = 0;
                    item.fetchList = {};
                end
                if freeNum < itemDataNum then
                    serveritems.curLeftRewardNum = itemDataNum - freeNum;
                    break;
                elseif costItem.f_BeHindId == 0 then
                    break;
                elseif item.buyCount > 0 and #item.fetchList < itemDataNum then
                    break;
                else
                    if tableData[tostring(costItem.f_BeHindId)] == nil then
                        break;
                    end
                    costItem = tableData[tostring(costItem.f_BeHindId)];
                    freeNum = freeNum - itemDataNum;
                end
                flag = flag + 1;
            end
            serveritems.subId = item.subId;
            serveritems.buyCount = item.buyCount;
            serveritems.money = costItem.f_Price;
            serveritems.payId = costItem.f_ProductId;
            serveritems.title = costItem.f_Title;
            if costItem.f_BeHindId == 0 then
                serveritems.preTitle = "";
            else
                local nextCfg = tableData[tostring(costItem.f_BeHindId)];
                if nextCfg == nil then
                    serveritems.preTitle = "";
                else
                    serveritems.preTitle = nextCfg.f_Title;
                end
            end

            serveritems.items = {};
            serveritems.nowChapter=nowCurrent
            local allRewardItems={}
            local canGetRewardItems={}
            local function AddReward(t,id,num)
                if t[id]==nil then
                    t[id]=num
                else
                    t[id]=t[id]+num
                end
            end
            local function ConvertRewardList(t)
                local temp={}
                for k,v in pairs(t)do
                    table.insert(temp,{k,v})
                end
                return temp
            end
            for key, value in pairs(itemData) do
                local data = {};
                data.subId = value.f_ItemId;
                if stageConfig[tostring(value.f_NeedClearStage)] ~= nil then
                    data.chapter = stageConfig[tostring(value.f_NeedClearStage)].f_ChapterId;
                    data.progress = math.min(nowCurrent, data.chapter);
                    if nowCurrent < data.chapter then
                        data.receiveState = 0;
                    elseif (not freeStates[value.f_ItemId])then
                        data.receiveState=1
                        serveritems.redDots = true
                    elseif CostManager.isExistInListByValue(item.fetchList, data.subId) then
                        data.receiveState = 2;
                    else
                        if serveritems.buyCount > 0 then
                            serveritems.redDots = true;
                        end
                        data.receiveState = 3;
                    end
                    table.insert(serveritems.items, data);
                    local flag1=data.chapter<=nowCurrent and serveritems.buyCount<=0
                    local reward=value.f_Reward[1]
                    if flag1 then
                        AddReward(canGetRewardItems,reward[1],reward[2])
                    end
                    AddReward(allRewardItems,reward[1],reward[2])
                end
            end
            serveritems.allRewardItems=ConvertRewardList(allRewardItems)
            serveritems.canGetRewardItems=ConvertRewardList(canGetRewardItems)
            table.sort(serveritems.items, function (a, b)
                --if a.receiveState == 2 and b.receiveState == 2 or a.receiveState ~= 2 and b.receiveState ~= 2 then
                --    return a.chapter < b.chapter;
                --else
                --    return a.receiveState ~= 2;
                --end
                return a.chapter < b.chapter;
            end);
            return serveritems, itemData, modelTableData;
        end
    end
    return serveritems, itemTableData, modelTableData;
end

---处理战令系统数据
function CostManager.disposeBattlePassData(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local battleTotal = 0;
    if tonumber(modelTableData.f_NeedItem) == 0 then
        battleTotal = serverData.marketData.loginDay or 0;
    else
        battleTotal = logicMgr.ItemManager.getBagNumByTableID(modelTableData.f_NeedItem);
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    serveritems.items = {};
    if serverData.marketData.fetchMap == nil then
        serverData.marketData.fetchMap = {};
    end
    local battleClass = serverData.marketData.battlePassLv;
    if battleClass == nil or battleClass == 0 then
        local value = G.dataTable["t_global"][tostring(231)].f_int_value / 24/60/60;
        local openTimeStatus = serverData.startTime;
        if openTimeStatus == nil then
            battleClass = 1;
        else
            local serverTime = HelperFunc.GetServerTime();
            battleClass = math.floor((serverTime - openTimeStatus + value) / value);
            battleClass = math.min(modelTableData.f_MaxLv, battleClass);
        end
    end
    local battleType = serverData.marketData.battlePassType;
    if battleType == nil or battleType == 0 then
        serveritems.canChange = 1;
        battleType = modelTableData.f_ItemType;
    end
    local subTableData = {};
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == activeId and v.f_Class == battleClass and v.f_RewardType == battleType then
            table.insert(subTableData, v);
        end
    end
    table.sort(subTableData, function (a, b) return a.f_Order < b.f_Order end);
    serveritems.subId = activeId;
    serveritems.items = {};
    serveritems.progress = battleTotal;
    serveritems.class = battleClass;
    serveritems.type = battleType;
    serveritems.nextResetTime = serverData.marketData.nextResetTime;
    serveritems.buyCount = serverData.marketData.buyCount or 0;
    local isNoEnough = false;
    for k, v in pairs(subTableData) do
        local fetch = serverData.marketData.fetchMap[tostring(v.f_ItemId)];
        local item = {};
        item.subId = v.f_ItemId;
        if fetch == nil then
            fetch = 0;
        end
        if fetch == 2 then
            item.receiveState = 2;
        elseif fetch == 1 then
            if serveritems.buyCount >= 1 then
                if serveritems.nowCanReceiveIndex == nil then
                    serveritems.nowCanReceiveIndex = k;
                end
                item.receiveState = 4;
                serveritems.redDots = true;
            else
                item.receiveState = 3;
            end
        end
        table.insert(serveritems.items, item);
        if k == #subTableData then
            item.isLast = true;
        elseif k == 1 then
            item.isFrist = true;
        end
        if isNoEnough then
            item.upNum = 0;
            item.downNum = 0;
            item.receiveState = 0;
            if serveritems.nowCanReceiveIndex == nil then
                serveritems.nowCanReceiveIndex = k;
            end
        else
            item.downNum = 0;
            if battleTotal < v.f_NeedPoint then
                item.receiveState = 0;
                if serveritems.nowCanReceiveIndex == nil then
                    if serveritems.buyCount >= 1 then
                        serveritems.nowCanReceiveIndex = k;
                    else
                        serveritems.nowCanReceiveIndex = 1;
                    end
                end
                isNoEnough = true;
                if item.isFrist == nil then
                    local lastNum = subTableData[k-1].f_NeedPoint;
                    local numm = math.floor((battleTotal-lastNum)*200/(v.f_NeedPoint-lastNum));
                    serveritems.items[k - 1].downNum = math.min(numm, 100);
                    item.upNum = math.max(numm - 100, 0);
                else
                    item.upNum = math.floor(battleTotal * 100 / v.f_NeedPoint);
                end
                serveritems.needBPIndex = k;
            else
                item.upNum = 100;
                if item.isFrist == nil then
                    serveritems.items[k - 1].downNum = 100;
                end
                if item.receiveState == nil then
                    item.receiveState = 1;
                    serveritems.redDots = true;
                    if serveritems.nowCanReceiveIndex == nil then
                        serveritems.nowCanReceiveIndex = k;
                    end
                end
            end
        end
    end
    if serveritems.nowCanReceiveIndex == nil then
        serveritems.nowCanReceiveIndex = 1;
    end
    return serveritems, tableData, modelTableData;
end

---处理充值数据
function CostManager.disposeGiftVip(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    if logicMgr.VipManager.GetVipIsHave() then
        serveritems.redDots = true;
    end
    serveritems.items = {};
    if serverData.marketData.buyCountMap == nil then
        serverData.marketData.buyCountMap = {};
    end
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == activeId then
            local item = {};
            item.subId = v.f_ItemId;
            item.order = v.f_Order;
            item.buyCount = serverData.marketData.buyCountMap[tostring(v.f_ItemId)];
            if item.buyCount == nil then
                item.buyCount = 0;
            end
            table.insert(serveritems.items, item);
        end
    end
    table.sort(serveritems.items, function (a, b) return a.order < b.order end);
    return serveritems, tableData, modelTableData;
end

---处理贵族特权数据
function CostManager.disposePrivilege(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local serveritems = {};
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.redDots = this.getActiveOpenStatus(activeId);
    if serverData.marketData.endTime ~= nil then
        serveritems.overTime = tonumber(tostring(serverData.marketData.endTime)) * 0.001;
    else
        serveritems.overTime = 0;
    end

    serveritems.bugCount = serverData.marketData.buyTimes or 0;
    local ttable = {}
    for k, v in pairs(tableData) do
        if v.f_BelongActiveId == activeId then
            table.insert(ttable, v);
        end
    end
    table.sort(ttable, function (a, b) return a.f_ItemId < b.f_ItemId end);
    return serveritems, ttable, modelTableData;
end

--添加贵族特权buff
function CostManager.addPrivilegeBuff()
    local severData, itemData, modelTableData;
    severData, itemData, modelTableData = this.getCostData(logicMgr.CostManager._PRIVILEGE);
    if this.privilegeTime ~= nil then
        utimer.remove(this.privilegeTime);
        this.privilegeTime = nil;
    end
    if severData == nil or itemData == nil or modelTableData == nil then
        return;
    end
    if severData ~= nil and severData.overTime < 0 then
        logicMgr.EcoBuffManager.updateEcoBuff(EnumConst.EcoBuffType.Nobility, decodeJsonStrToTabel(modelTableData.f_NobleBuff));
        return;
    end
    if severData == nil or severData.overTime <= HelperFunc.GetServerTime() then
        return;
    end
    logicMgr.EcoBuffManager.updateEcoBuff(EnumConst.EcoBuffType.Nobility, decodeJsonStrToTabel(modelTableData.f_NobleBuff));
    this.privilegeTime = utimer.timeCall(function()
        logicMgr.EcoBuffManager.updateEcoBuff(EnumConst.EcoBuffType.Nobility, {});
        this.privilegeTime = nil;
    end, (severData.overTime - HelperFunc.GetServerTime()) * 1000, 1);
end

--处理每日限定数据
function CostManager.disposeGiftDay(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId);
    if serverData == nil or tableData == nil then
        return {}, {};
    end
    local localServerData = {};
    localServerData.startTime = serverData.startTime;
    localServerData.endTime = serverData.endTime;
    localServerData.drawEndTime = serverData.drawEndTime;
    localServerData.redDots = this.getActiveOpenStatus(activeId);
    localServerData.hasBuyMap = {};
    if serverData.marketData.hasBuyMap ~= nil then
        localServerData.hasBuyMap = serverData.marketData.hasBuyMap;
    end
    local giftEndTime = serverData.marketData.allGiftEndTime or 0;
    giftEndTime = math.ceil(giftEndTime * 0.001);
    localServerData.hasBuy = false;
    local giftStartTime = serverData.marketData.allGiftStartTime or 0;
    giftStartTime = math.ceil(giftStartTime * 0.001);
    if giftStartTime > 0 then
        localServerData.hasBuy = true;
    end
    localServerData.giftEndTime = giftEndTime;
    localServerData.giftStartTime = giftStartTime;
    localServerData.hasEffect = false;
    local serverTime = HelperFunc.GetServerTime();
    if serverTime > giftStartTime and serverTime < giftEndTime then
        localServerData.hasEffect = true;
    end

    if serverTime >= giftEndTime then
        localServerData.hasBuy = false;
        localServerData.hasEffect = false;
    end

    local hasGetAllReward = true;
    local tableItems = {};
    local consumeClass = this.getPlayerConsumeClass();
    for k, v in pairs(tableData) do
        local productType = tonumber(v.f_ProductType);
        local buyCount = localServerData.hasBuyMap[tostring(v.f_ItemId)] or 0;
        local limitCount = tonumber(v.f_Count)
        if productType == 1 then
            if consumeClass >= tonumber(v.f_NeedRencencyLevel) then
                local item = v;
                item.residue = 1;
                if buyCount >= limitCount then
                    item.residue = 0;
                else
                    hasGetAllReward = false;
                end
                table.insert(tableItems, item);
                if v.f_Price == 0 then
                    if buyCount < limitCount then
                        localServerData.redDots = true;
                    end
                else
                    if localServerData.hasEffect and buyCount < limitCount then
                        localServerData.redDots = true;
                    end
                end
            end
        elseif productType == 2 then
            localServerData.tableItem = v;
        end
    end
    table.sort(tableItems, function(a, b)
        if a.residue == b.residue then
            return a.f_Order < b.f_Order;
        else
            return a.residue > b.residue;
        end

    end)
    localServerData.hasGetAllReward = hasGetAllReward;
    return localServerData, tableItems, modelTableData;
end

--disposeGiftHero 英雄突破活动礼包
function CostManager.disposeGiftHero(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId)
    if serverData == nil or tableData == nil then return {}, {} end

    local serveritems = {}
    serveritems.startTime = serverData.startTime
    serveritems.endTime = serverData.endTime
    serveritems.drawEndTime = serverData.drawEndTime
    serveritems.items = {}
    serveritems.redDots = false
    if serverData.marketData.dataMap == nil then
        serverData.marketData.dataMap = {}
    end

    local vip_level = logicMgr.VipManager.getVipLevel() 
    for k, v in pairs(tableData) do  
        if v.f_BelongActiveId == activeId then 
            local show_vip_condition = true
            if vip_level < v.f_VipCondition then 
                show_vip_condition = false
            end
            local show_condition = true
            if show_vip_condition == false then
                local hero_data = decodeJsonStrToTabel(v.f_RankCondition) or {} 
                if hero_data[1] ~= nil then
                    local is_own_hero = HeroManager.IsHaveByPartnerModelId( hero_data[1] )
                    if is_own_hero then
                        local star = HeroManager.GetHeroStarByPartnerModelId(hero_data[1])
                        if star < tonumber(hero_data[2]) then
                            show_condition = false
                        end
                    else
                        show_condition = false
                    end
                end
            end
            if show_vip_condition or show_condition then
                local item = {}
                item.hero = v.f_Hero
                item.vip_condition = v.f_VipCondition
                item.base_reward = v.f_BaseReward
                item.advanced_reward = v.f_AdvancedReward
                item.buy_price = v.f_Price
                item.buy_count = v.f_Count
                item.item_id = v.f_ItemId
                item.order = v.f_Order
                item.product_id = v.f_ProductId
                -- item.rank_condition = decodeJsonStrToTabel(v.f_RankCondition) -- 
                -- item.belong_activeid = v.f_BelongActiveId 
                local item_id_key = tostring(item.item_id)
                item.get_free_count = serverData.marketData and serverData.marketData.freeGiftTimes and serverData.marketData.freeGiftTimes[item_id_key] or 0
                item.get_buy_count = serverData.marketData and serverData.marketData.giftTimes and serverData.marketData.giftTimes[item_id_key] or 0
                table.insert(serveritems.items, item)
                if serveritems.redDots ~= true and item.get_free_count <= 0 and  item.get_buy_count < item.buy_count then 
                    local hero_item = v.f_Hero
                    local star = HeroManager.GetHeroStarByPartnerModelId(hero_item[1])
                    if star >= tonumber(hero_item[2]) then
                        serveritems.redDots = true
                    end
                end
            end 
        end
    end
    if serveritems.endTime <= Config.serverTime/1000 then
        serveritems.redDots = false
    end
    table.sort(serveritems.items, function (a, b) return a.order < b.order end)
    return serveritems, modelTableData
end

--快捷购买
function CostManager.disposeFastConsumption(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId)
    if serverData == nil or tableData == nil then
        return nil;
    end

    local serveritems = {}
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.items = {};
    serveritems.redDots = false;
    serveritems.hasBuy = false;
    local serverBuyMarketSet = serverData.marketData.buyMarketSet;
    local buyMarketSet = {};
    if serverBuyMarketSet ~= nil then
        for k, v in pairs(serverBuyMarketSet) do
            buyMarketSet[tostring(v)] = 1;
        end
    end

    for k, v in pairs(tableData) do
        table.insert(serveritems.items, v);
        if buyMarketSet[tostring(v.f_ItemId)] ~= nil and buyMarketSet[tostring(v.f_ItemId)] > 0 then
            serveritems.hasBuy = true;
        end
    end

    return serveritems, modelTableData, serverData;
end

--七日排行榜快捷购买
function CostManager.disposeSevenRankPlusFastConsumption(activeId)
    local serverData, tableData, modelTableData = this.getCostInitialDataById(activeId)
    if serverData == nil or tableData == nil then
        return nil;
    end

    local serveritems = {}
    serveritems.startTime = serverData.startTime;
    serveritems.endTime = serverData.endTime;
    serveritems.drawEndTime = serverData.drawEndTime;
    serveritems.items = {};
    serveritems.redDots = false;
    local serverBuyMarket
    if serverData.marketData.buyTimes == nil then
        serverBuyMarket = {};
    else
        serverBuyMarket = serverData.marketData.buyTimes;
    end

    for k, v in pairs(tableData) do
        local serverItem = {};
        local buyCount = serverBuyMarket[tostring(v.f_RaceRankBagId)];
        serverItem.f_ItemId = v.f_RaceRankBagId;
        serverItem.buyCount = buyCount or 0;
        serverItem.typeId = v.f_TypeId;
        serverItem.residue = v.f_Count - serverItem.buyCount;
        serverItem.f_ProductName = v.f_ProductName;
        if serverItem.money == 0 and serverItem.residue > 0 then
            serveritems.redDots = true;
        end
        table.insert(serveritems.items, serverItem);
    end

    table.sort(serveritems.items, function(a, b)
        if a.residue <= 0 and b.residue <= 0 or a.residue > 0 and b.residue > 0 then
            if a.money == 0 and b.money == 0 then
                return a.f_ItemId < b.f_ItemId;
            elseif a.money == 0 or b.money == 0 then
                return a.money < b.money;
            else
                return a.f_ItemId < b.f_ItemId;
            end
        else
            return a.residue > 0;
        end
    end)
    return serveritems, modelTableData, serverData;
end

-- 判断快捷购买状态 -1:未开启, 0:已开启, 1:已结束
function CostManager.getFastConsumption()
    --local configValues = {};
    --configValues[1] = logicMgr.HeroManager.GetRoleLevel();
    --configValues[2] = logicMgr.MapManager.getMapId();
    --configValues[6] = (HelperFunc.GetServerTime() - logicMgr.ActiveManager.getDataUpateTime(tonumber(tostring((logicMgr.LoginManager.GetServerOpenTime()/1000)))))/86400;
    local activeTable = activeTableData[tostring(this._FASTCONSUMPTION)] or {};
    if not this.isOpenItem(activeTable) then
        return -1;
    end
    --if activeTable.f_AndRelation ~= "" then
    --    local andRelation = decodeJsonStrToTabel(activeTable.f_AndRelation);
    --    for k, v in pairs(andRelation) do
    --        if configValues[v[1]] < v[2] then
    --            return -1;
    --        end
    --    end
    --end
    local serverData = this.disposeFastConsumption(this._FASTCONSUMPTION);
    if serverData == nil or serverData.hasBuy or HelperFunc.GetServerTime() > serverData.endTime then
        return 1;
    elseif HelperFunc.GetServerTime() < serverData.startTime then
        return -1;
    else
        return 0;
    end
end

-- 判断快捷购买是否有列表
function CostManager.isFastConsumptionItems(type, heroId)
    local selectedItems = {};
    local buyType = tonumber(type)
    for k, v in pairs(payDataTable) do
        local quickBuy = v["f_QuickBuy" .. buyType];
        if quickBuy ~= nil and tonumber(quickBuy) > 0 and (v.f_BeforeConsumptionID == nil or tonumber(v.f_BeforeConsumptionID) == 0) then
            if buyType == 4 then
                if v.f_HeroId == nil or tonumber(v.f_HeroId) == 0 or tonumber(v.f_HeroId) == tonumber(heroId) then
                    table.insert(selectedItems, v);
                end
            else
                table.insert(selectedItems, v);
            end
        end
    end
    local serverDataTab = {};
    for i = 1, #selectedItems do
        local item = selectedItems[i];
        local fromActivityId = tostring(item.f_FromActivityId);
        if serverDataTab[fromActivityId] == nil then
            local serverData = this.getActiveServerDataList(item.f_FromActivityId);
            local serverTime = HelperFunc.GetServerTime();
            local localServerData = {};
            if serverData == nil or serverTime < serverData.startTime or (serverData.drawEndTime > 0 and serverTime > serverData.drawEndTime) then
                localServerData.serverData = nil;
            else
                localServerData.serverData = serverData;
            end
            serverDataTab[fromActivityId] = localServerData;
        end
        local serverDataItem = serverDataTab[fromActivityId].serverData;
        local tableData, localServerData = this.getTableData(fromActivityId, item.f_ItemId, serverDataItem);
        if tableData ~= nil and localServerData.residue ~= nil then
            if tableData.f_Num == -1 or localServerData.countSum == nil or tonumber(localServerData.countSum) > 0 or (localServerData.residue <= 0 and tonumber(localServerData.countSum) <= 0) then
                local localBuyItem = {};
                if localServerData.residue > 0 or item.f_NextConsumptionID == nil or tonumber(item.f_NextConsumptionID) == 0 then
                    localBuyItem.tableData = tableData;
                    localBuyItem.serverData = localServerData;
                else
                    local backTableData, backLocalServerData = this.getNextConsumptionData(tableData, localServerData, item, serverDataItem, buyType);
                    localBuyItem.tableData = backTableData;
                    localBuyItem.serverData = backLocalServerData;
                end
                return true;
            end
        end
    end
    return false;
end

function CostManager.getTableData(storeId, itemId, serverData)
    if storeId == nil then
        return nil;
    end
    local modelTableData = nil;
    local tableDataItem = nil;

    local activeTable = serverTableData[tostring(storeId)] or {};
    local storeentrance = activeTableData[tostring(storeId)];
    if storeentrance ~= nil then
        if storeentrance.f_ModelName == nil or storeentrance.f_ModelName == "" then
            return nil;
        end
        modelTableData = G.dataTable[storeentrance.f_ModelName][tostring(storeId)];
        if modelTableData == nil then
            return nil;
        end
    else
        return nil;
    end

    local tableDataCfg = G.dataTable[modelTableData.f_ItemTableName];
    if tableDataCfg ~= nil then
        tableDataItem = tableDataCfg[tostring(itemId)];
    else
        return nil;
    end
    if tableDataItem == nil then
        return nil;
    end

    local type = tonumber(activeTable.f_StoreType);
    local tableData = {};
    local localServerData = {};
    localServerData.residue = nil;
    localServerData.countSum = nil;

    if type == 3 then
        if not this.isOpenItem(tableDataItem) then
            return nil;
        end
        tableData = tableDataItem;
        tableData.f_StoreType = type;

        if serverData ~= nil then
            local buyCountMap = {};
            local buyCountSumMap = {};
            if serverData.marketData ~= nil then
                if serverData.marketData.buyCountMap ~= nil then
                    buyCountMap = serverData.marketData.buyCountMap;
                end
                if serverData.marketData.buyCountSumMap ~= nil then
                    buyCountSumMap = serverData.marketData.buyCountSumMap;
                end
            end
            if tableData.f_Num ~= -1 then
                local countSum = buyCountSumMap[tostring(tableData.f_ItemId)] or 0;
                local cfgNum = tableData.f_Num;
                if countSum < cfgNum then
                    localServerData.countSum = cfgNum - countSum;
                else
                    localServerData.countSum = -10;
                end
            end
            local buyCount = buyCountMap[tostring(tableData.f_ItemId)] or 0;
            localServerData.residue = tableData.f_Count - buyCount;
        end
        return tableData, localServerData;
    elseif type == 13 then
        tableData = this.getTableDataModel();
        tableData.f_ItemId = tableDataItem.f_ItemId;
        tableData.f_BelongActiveId = tableDataItem.f_StoreId;
        tableData.f_Price = tableDataItem.f_Price;
        tableData.f_OriginPrice = tableDataItem.f_OriginPrice;
        tableData.f_Count = tableDataItem.f_Count;
        tableData.f_ProductId = tableDataItem.f_ProductId;
        tableData.f_MajorCommodityReward = tableDataItem.f_MajorCommodityReward;
        tableData.f_CommonCommodityReward = tableDataItem.f_CommonCommodityReward;
        tableData.f_StoreType = type;

        if serverData ~= nil then
            local buyMarketSet = {};
            if serverData.marketData ~= nil then
                local serverBuyMarketSet = serverData.marketData.buyMarketSet;
                if serverBuyMarketSet ~= nil then
                    for k, v in pairs(serverBuyMarketSet) do
                        buyMarketSet[tostring(v)] = 1;
                    end
                end
            end
            local buyCount = buyMarketSet[tostring(tableData.f_ItemId)] or 0;
            localServerData.residue = tableData.f_Count - buyCount;
        end
        return tableData, localServerData;
    elseif type == 15 then
        tableData = this.getTableDataModel();
        tableData.f_ItemId = tableDataItem.f_RaceRankBagId;
        tableData.f_BelongActiveId = tableDataItem.f_StoreId;
        tableData.f_Price = tableDataItem.f_Price;
        tableData.f_OriginPrice = tableDataItem.f_OriginPrice;
        tableData.f_Count = tableDataItem.f_Count;
        tableData.f_ProductId = tableDataItem.f_ProductId;
        tableData.f_MajorCommodityReward = tableDataItem.f_MajorCommodityReward;
        tableData.f_CommonCommodityReward = tableDataItem.f_CommonCommodityReward;
        tableData.f_StoreType = type;
        tableData.f_PriceType = tableDataItem.f_PriceType;

        if serverData ~= nil then
            local buyMarketSet = {};
            if serverData.marketData ~= nil then
                if serverData.marketData.buyTimes ~= nil then
                    buyMarketSet = serverData.marketData.buyTimes;
                end
            end
            local buyCount = buyMarketSet[tostring(tableData.f_ItemId)] or 0;
            localServerData.residue = tableData.f_Count - buyCount;
        end
        return tableData, localServerData;
    else
        return nil;
    end
end

function CostManager.getTableDataModel()
    local tableData = {};
    tableData.f_ItemId = 0;
    tableData.f_BelongActiveId = 0;
    tableData.f_Price = 0;
    tableData.f_Count = 1;
    tableData.f_Num = -1;
    tableData.f_MajorCommodityReward = "";
    tableData.f_CommonCommodityReward = "";
    tableData.f_ActivityId = "";
    tableData.f_NewMajorCommodityReward = "";
    tableData.f_BgPic = "";
    tableData.f_title = "";
    tableData.f_NextConsumptionID = 0;
    tableData.f_BeforeConsumptionID = 0;
    tableData.f_Order = 0;
    tableData.f_AndRelation = "";
    tableData.f_OrRelation = "";
    tableData.f_NeedRencencyLevel = 0;
    tableData.f_UnlockStage = 0;
    tableData.f_UnlockTime = 0;
    tableData.f_UnlockVipRank = 0;
    tableData.f_ProductId = 0;
    tableData.f_Type = 0;
    tableData.f_BannerHeroHead = "";
    tableData.f_OriginPrice = 0;
    tableData.f_Discount = 0;
    return tableData;
end

function CostManager.getNextConsumptionData(backTableData, backServerData, cfg, serverData, buyType)
    local itemCfg = payDataTable[tostring(cfg.f_NextConsumptionID)];
    if itemCfg == nil or itemCfg.f_FromActivityId ~= cfg.f_FromActivityId then
        return backTableData, backServerData;
    end
    local tableData, localServerData = this.getTableData(itemCfg.f_FromActivityId, itemCfg.f_ItemId, serverData);
    if tableData == nil or localServerData.residue == nil then
        return backTableData, backServerData;
    end
    local quickBuy = itemCfg["f_QuickBuy"..buyType];
    if localServerData.residue > 0 then
        if quickBuy ~= nil and tonumber(quickBuy) > 0 then
            if localServerData.countSum == nil or localServerData.countSum > 0 then
                return tableData, localServerData;
            else
                return backTableData, backServerData;
            end
        else
            return backTableData, backServerData;
        end
    else
        if itemCfg.f_NextConsumptionID == nil or tonumber(itemCfg.f_NextConsumptionID) == 0 then
            if quickBuy ~= nil and tonumber(quickBuy) > 0 then
                return tableData, localServerData;
            else
                return backTableData, backServerData;
            end
        else
            return this.getNextConsumptionData(tableData, localServerData, itemCfg, serverData, buyType);
        end
    end
end
--------------------------------------------------------------------------------------
function CostManager.updateCostHelp(root, obj, modelTableData)
    if root == nil or obj == nil then
        return ;
    end
    if modelTableData.f_ExplainText == nil or modelTableData.f_ExplainText == "" or modelTableData.f_ExplainTitle == nil or modelTableData.f_ExplainTitle == "" then
        obj.visible = false;
    else
        obj.visible = true;
        root:RegisterOnClick(obj, function ()
            logicMgr.UIShowManager.ShowCommonTips(modelTableData.f_ExplainTitle, modelTableData.f_ExplainText);
        end);
    end
end

function CostManager.getFunMenuById(id)
    local sevenData, tableData, modelTableData = logicMgr.CostManager.getCostData(id);
    if sevenData ~= nil and sevenData.canShow then
        local flag = {};
        tableData = logicMgr.CostManager.getCostTableDataById(id);
        flag.f_ID = id;
        flag.id = id;
        flag.f_FuntionType = 1;
        flag.f_Icon = modelTableData.f_MenuIcon;
        flag.f_OpenUI = tableData.f_Interface;
        flag.f_Desc = modelTableData.f_MenuName;
        flag.f_HintType = Config.RedDotsType.Cost;
        flag.f_FuncOpen = "";
        return flag;
    else
        return nil;
    end
end
function CostManager.getFirstPayData(id)
    local modelTableData = G.dataTable["t_firstrechargereward"][tostring(id)];
    if modelTableData ~= nil then
        local flag = {};
        flag.f_ID = id;
        flag.id = id;
        flag.f_FuntionType = 1;
        flag.f_Icon = modelTableData.f_MenuIcon;
        flag.f_OpenUI = modelTableData.f_OpenUI;
        flag.f_Desc = modelTableData.f_MenuName;
        flag.f_HintType = Config.RedDotsType.FirstPayGift;
        flag.f_FuncOpen = "";
        return flag;
    end
end

function CostManager.setOpenCondition()
    this.configValues = {};
    this.configValues[1] = logicMgr.CostManager.getPlayerConsumeClass()
    this.configValues[2] = logicMgr.MapManager.getMapId()
    this.configValues[3] = math.ceil((HelperFunc.GetServerTime() - logicMgr.ActiveManager.getDataUpateTime(tonumber(tostring((logicMgr.LoginManager.GetServerOpenTime()/1000)))))/86400);
    this.configValues[4] = logicMgr.VipManager.getVipLevel()
end

function CostManager.isOpenItem(singleConfig, showTips)
    if singleConfig == nil or singleConfig == "" or next(singleConfig) == nil then
        return true;
    end
    if this.configValues == nil then
        this.setOpenCondition();
    end
    if singleConfig.f_AndRelation and singleConfig.f_AndRelation ~= "" then
        local andRelation = decodeJsonStrToTabel(singleConfig.f_AndRelation);
        for k, v in pairs(andRelation) do
            if this.configValues[v] < singleConfig[this.configKeys[v]] then
                if showTips then
                    this.showLockTip(v, singleConfig[this.configKeys[v]]);
                end
                return false, this.showLockTip(v, singleConfig[this.configKeys[v]], true);
            end
        end
        return true;
    end
    if singleConfig.f_OrRelation and singleConfig.f_OrRelation ~= "" then
        local orRelation = decodeJsonStrToTabel(singleConfig.f_OrRelation);
        for k, v in pairs(orRelation) do
            if this.configValues[v] >= singleConfig[this.configKeys[v]] then
                return true;
            end
        end
        if next(orRelation) and showTips then
            this.showLockTip(orRelation[1], singleConfig[this.configKeys[orRelation[1]]]);
            return false, this.showLockTip(orRelation[1], singleConfig[this.configKeys[orRelation[1]]], true);
        end
        return false, "";
    end
    return true;
end

function CostManager.showLockTip(index, param, re)
    local _text = "";
    if index == 2 then
        local config = G.dataTable["t_stage"][tostring(param)];
        if config ~= nil then
            local str = config.f_ChapterId .. "-" .. config.f_StageNum;
            _text = string.format(getLanguage("Sys_OptionalPoolLocked2"), str);
        else
            printError("t_stage 集市缺少解锁关卡 ", param);
        end
    elseif index == 3 then
        _text = param - this.configValues[3] .. getLanguage("FunctionSwitchUnlockTips3") .. getLanguage("FunctionSwitchUnlockTips2");
    elseif index == 4 then
        _text = string.format(getLanguage("FunctionTipsVip"), param) .. getLanguage("FunctionSwitchUnlockTips2");
    end
    if re then
        return _text;
    else
        UISysTips.AddMsg(_text);
    end
end

function CostManager.itemIsOpen(id, showTips)
    return this.isOpenItem(itemLimitTableData[tostring(id)], showTips);
end
---------------------------------------------------- 登陆弹窗类 ----- 开始---------------------
--- 只做活动登陆弹窗展示，其他弹窗需要重新开发，活动弹窗可以当做一个整体弹窗，不影响后续开发通用登陆弹窗。
--糊脸公告点击前往后续弹框不弹了
function CostManager.resetActivePopUpTips()
    waitPopTips = {};
    isNeedShowPopUpTips = false;
end

function CostManager.startActivePopUpTips()
    if logicMgr.GuideMgr.IsGuiding() or not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Cost) then
        waitPopTips = {};
        isNeedShowPopUpTips = false;
        return;
    end
    if isNeedShowPopUpTips == nil or isNeedShowPopUpTips then
        isNeedShowPopUpTips = false;
        local lastTime = Util.GetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId.."_LastActivePopUpTipsTime");
        if lastTime == nil then
            lastTime = 0;
        end
        lastTime = tonumber(lastTime);
        local time = HelperFunc.GetServerTime();
        if time - lastTime >= G.dataTable["t_global"][tostring(271)].f_int_value and waitPopTips ~= nil and #waitPopTips > 0 then
            Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId.."_LastActivePopUpTipsTime", time);
        else
            waitPopTips = {};
        end
        CostManager.showPopUpTips();
    end
end

function CostManager.addPopUpTips(uiName, id)
    if not isNeedShowPopUpTips then
        waitPopTips = {};
        return;
    end
    if waitPopTips == nil then
        waitPopTips = {};
    end
    local data = {};
    data.uiName = uiName;
    data.activeId = id;
    table.insert(waitPopTips, data);
end

function CostManager.showPopUpTips()
    if waitPopTips ~= nil and #waitPopTips > 0 then
        local data = waitPopTips[1];
        table.remove(waitPopTips, 1);
        local name = PanelNames[data.uiName];
        if name == nil then
            CostManager.showPopUpTips()
            return;
        end
        if not isOpenUI(name) then
            showUI(name, nil, data.activeId);
        end
    --else
    --    logicMgr.ActiveManager.startActivePopUpTips();
    end
end
---------------------------------------------------- 登陆弹窗类 ----- 结束---------------------

-------------------------服务端数据处理----------开始-------------
function CostManager.RefreshItemList(list, itemData, maxNum, data)
    list:RemoveChildrenToPool()
    if itemData == nil then
        return;
    end
    for i = 1, #itemData do
        local item = list:AddItemFromPool()
        CostManager.RefreshItem(item, itemData[i], data);
    end
    if maxNum ~= nil then
        if #itemData > maxNum then
            list.scrollPane.touchEffect = true;
        else
            list.scrollPane.touchEffect = false;
        end
    end
end

function CostManager.RefreshItem(itemGo, itemValue, data)
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
    if ctrlItem ~= nil and itemValue[1] then
        ctrlItem.initData(itemGo,this.getItemOrEquipDataByIdAndNum(itemValue[1], itemValue[2], data));
    end
end

function CostManager.getItemOrEquipDataByIdAndNum(id, num, data)
    local singleItemConfig;
    if logicMgr.ItemManager.IsEquip(id) then
        singleItemConfig = logicMgr.EquipManager.getEquipConstDatabyModelId(id);
    else
        singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(id);
    end
    if singleItemConfig ~= nil then
        singleItemConfig.num = tonumber(tostring(num));
    end
    if data ~= nil then
        for k, v in pairs(data) do
            singleItemConfig[k] = v;
        end
    end
    return singleItemConfig;
end
--
--function CostManager.findSeverItem(data, id)
--    if data == nil then
--        return false;
--    end
--    for k,v in pairs(data) do
--        if v.subId == id then
--            return v;
--        end
--    end
--    return false;
--end

function CostManager.findCostItem(data, id)
    if data == nil then
        return {};
    end
    for k,v in pairs(data) do
        if v.f_ItemId == id then
            return v;
        end
    end
    return {};
end

function CostManager.findTableDataByBelong(data, id)
    if data == nil then
        return {};
    end
    local list = {};
    for k,v in pairs(data) do
        if v.f_BelongActiveId == id then
            table.insert(list, v);
        end
    end
    return list;
end

function CostManager.isExistInListByValue(data, id)
    if data == nil then
        return false;
    end
    for k,v in pairs(data) do
        if v == id then
            return true;
        end
    end
    return false;
end

function CostManager.updateLiHui(self, drawWrapper, lihui, lihui2, heroIdData)
    if heroIdData == nil or heroIdData == "" then
        return ;
    end
    local _type = 1;
    local heroId = heroIdData;
    local objX = nil;
    local objY = nil;
    local objScale = nil;
    local idle = nil;
    if type(heroIdData) == "table" then
        local data = decodeJsonStrToTabel(heroIdData);
        _type = data[2];
        heroId = data[1];
        idle = data[3];
        objX = data[4];
        objY = data[5];
        objScale = data[6];
    end
    if _type == 1 then
        -- 英雄Id
        local path = logicMgr.HeroManager.GetHeroDrawingPath(heroId or 1);
        resMgr:LoadModelPrefab(path, function(go)
            if(self.RoleLihui~=nil)then
                destroyImmediate(self.RoleLihui);
                self.RoleLihui = nil
            end
            self.RoleLihui = newObject(go);
            self.RoleLihui.name = path;
            --Util.AddAction(self.RoleLihui,"idle1",true,0.5);
            self.RoleLihui:AddComponent(TCanvas);
            drawWrapper:SetWrapTarget(self.RoleLihui,false);
            local scale, location = HeroManager.GetHeroLocationResize(heroId or 1)
            Util.Lua_SetLocalPositionXYZ(self.RoleLihui.transform, location[1], location[2], 0)
            Util.Lua_SetLocalScaleXYZ(self.RoleLihui.transform, scale[1]*lihui.scaleX, scale[2]*lihui.scaleY, 1)
            idle = idle or "idle1";
            self.RoleLihui:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, idle, true);
            lihui:SetNativeObject(drawWrapper);
        end)
    elseif _type == 2 then
        if objX ~= nil and objY ~= nil then
            lihui2:SetXY(objX, objY);
        end
        if objScale ~= nil then
            lihui2:SetScale(objScale, objScale);
        end
        local list = TablePool.Get()
        string_split(heroId,"/",list)
        AddUIPackageDepend(PanelResNames.UICost,"FUI/"..list[1])
        self._package = "FUI/"..list[1];
        TablePool.Release(list)
        lihui2.url ="ui://"..heroId;
        idle = idle or "idle";
        Util.PlayAction(lihui2.wrapTarget, idle, true);
    end
end

----- 解析服务端数据
--function CostManager.resolverSeverItem(data)
--    if data == nil then
--        return {};
--    end
--    if type(data) ~= "table" then
--        if data == "" then
--            return {};
--        end
--        return decodeJsonStrToTabel(data);
--    end
--    local items = {};
--    for k,v in pairs(data) do
--        table.insert(items, decodeJsonStrToTabel(v));
--    end
--    return items;
--end
-------------------------服务端数据处理----------结束-------------

-----监听玩家充值行为
--function CostManager.playerMoneyChange(money, time)
--    if money == nil or time == nil or money == 0 then
--        return ;
--    end
--    local startTime = this.getFirstRechargeTime();
--    if startTime == 0 then
--        this.setFirstRechargeNum(money);
--        this.setFirstRechargeTime(time);
--        logicMgr.CostOpenManager.updateActive(Config.CostOpenCondition.FirstCharge);
--        FireEvent(Config.EventType.Fresh_FirstPayGiftRedDot);
--    end
--    this.addRechargeSum(money);
--end

---开服时间
function CostManager.getOpenServerTime()
    return this.openServerTime or HelperFunc.GetServerTime();
end

---合服时间
function CostManager.getCombineServerTime()
    return this.combineServerTIme or HelperFunc.GetServerTime();
end

---累加充值额度
function CostManager.addRechargeSum(data)
    this.rechargeSum = this.getRechargeSum() + tonumber(data);
    CostManager.setPlayerBehaviorTime(Config.CostOpenCondition.AchievePrepaid, this.rechargeSum);
end

---充值额度
function CostManager.getRechargeSum()
    return this.rechargeSum or 0;
end

---累加消耗钻石的总数
function CostManager.addCostGoldSum(data)
    this.costGoldSum = this.getCostGoldSum() + tonumber(data);
    CostManager.setPlayerBehaviorTime(Config.CostOpenCondition.AchieveDiamond, this.costGoldSum)
end

---消耗钻石的总数
function CostManager.getCostGoldSum()
    return this.costGoldSum or 0;
end

---设置首充时间
function CostManager.setFirstRechargeTime(data)
    this.firstRechargeTime = tonumber(data);
end

---首充时间
function CostManager.getFirstRechargeTime()
    --return HelperFunc.GetServerTime() - 100000;
    return this.firstRechargeTime or 0;
end

---设置首充金额
function CostManager.setFirstRechargeNum(data)
    this.firstRechargeNum = tonumber(data);
end

---首充金额
function CostManager.getFirstRechargeNum()
    return this.firstRechargeNum or 0;
end

---设置玩家行为时间
function CostManager.setPlayerBehaviorTime(id, num)
    if CostManager.setLocalTimeById(id, num, HelperFunc.GetServerTime()) then
        logicMgr.CostOpenManager.updateActive(id);
    end
end

---本地储存是否存在
function CostManager.isHaveLocalTimeById(id, num)
    id = tostring(id);
    if localConditionTime[id] == nil then
        return false;
    end
    for k, v in pairs(localConditionTime[id]) do
        if v[1] == num then
            return true;
        end
    end
    return false;
end

---储存本地条件时间
function CostManager.setLocalTimeById(id, num, time)
    id = tostring(id);
    if this.isHaveLocalTimeById(id, num) then
        return false;
    end
    if localConditionTime[id] == nil then
        localConditionTime[id] = {};
    end
    local data = {};
    table.insert(data, num);
    table.insert(data, time);
    table.insert(localConditionTime[id], data);
    return true;
end

---获取本地条件时间
function CostManager.GetLocalTimeById(id, num)
    local minNum = -1;
    local minTime = false;
    id = tostring(id);
    if localConditionTime[id] == nil then
        localConditionTime[id] = {};
    end
    for k, v in pairs(localConditionTime[id]) do
        if v[1] >= num and (minNum == -1 or v[1] < minNum) then
            minNum = v[1];
            minTime = v[2];
        end
    end
    return minTime;
end


-- 获取服务器返利状态
function CostManager.GetServerRebateType(serverId)
    if serverRebateType == nil then
        serverRebateType = G.dataTable["t_servertype"];
    end

    if serverRebateType == nil then
        return 0;
    end

    local cfg = serverRebateType[tostring(1)]
    if cfg == nil then
        return 0;
    end

    return tonumber(cfg.f_ServerType);
end

-- 判断自己是否有返利资格
function CostManager.HasVoucherReward()
    local serverType = this.GetServerRebateType(AppConst.ServerId)
    if serverType == 0 then
        return false;
    end
    if serverType == 1 then
        return true;
    end

    if localVoucherReward == nil then
        localVoucherReward = G.dataTable["t_voucherreward"];
    end
    if localVoucherReward == nil then
        return false;
    end
    local cfg;
    local uid;
    if logicMgr.LoginManager.user_id then
        uid = logicMgr.LoginManager.user_id;
        cfg = localVoucherReward[tostring(uid)];
    end

    if cfg ~= nil then
        return true;
    end

    return false;
end

-- 代金券数据
function CostManager.SetVoucherData(data)
    voucherData = data;
end
function CostManager.GetVoucherData()
    return voucherData;
end
function CostManager.UpdateVoucherRecharge(num)
    --local serverType = this.GetServerRebateType(AppConst.ServerId)
    --if voucherData ~= nil and serverType == 1 then
    --    voucherData.recharge = voucherData.recharge + tonumber(num);
    --end
end
--
--function CostManager.resVipInfoMsg(msg)
--    this.vipLevel = tonumber(tostring(msg.vipLv));
--    this.vipExp = tonumber(tostring(msg.vipExp));
--    this.vipFetchList = msg.fetchLvList;
--    CostManager.setPlayerBehaviorTime(Config.CostOpenCondition.AchieveVip, this.vipLevel)
--    FireEvent(Config.EventType.VIPInfoUpdate);
--end

----
--function CostManager.getVipDrawReward(id, callBack, tb)
--    this.getRewardId = id;
--    this.getRewardCallBack = callBack;
--    this.getRewardtb = tb;
--    vipHandler.reqGetVipDrawReward(tonumber(id));
--end
--
-----用户消费等级
--function CostManager.getVipLevel()
--    return this.vipLevel or 0;
--end

-----用户消费等级
--function CostManager.getVipExp()
--    return this.vipExp or 0;
--end

-----用户消费等级
--function CostManager.getVipFetchList()
--    return this.vipFetchList or {};
--end

-----获取VIP等级，当前进度与上限，下一个等级
--function CostManager.GetVipInfo()
--    local vipExp = CostManager.getVipExp();
--    local nextLv = CostManager.GetVipTableDataByLv(CostManager.getVipLevel() + 1);
--    local nowLv = CostManager.GetVipTableDataByLv(CostManager.getVipLevel());
--    if nextLv == nil then
--        return nowLv.f_VipLevel, vipExp - nowLv.f_VipNeedExp;
--    end
--    if nowLv == nil then
--        nowLv = {};
--        nowLv.f_VipLevel = 0;
--        nowLv.f_VipNeedExp = 0;
--    end
--    return nowLv.f_VipLevel, vipExp - nowLv.f_VipNeedExp, nextLv.f_VipNeedExp, nextLv.f_VipLevel;
--end
--
-----获取VIP数据
--function CostManager.GetVipTableDataByLv(id)
--    for k, v in pairs(vipTableData) do
--        if id == v.f_VipLevel then
--            return v, this.isExistInListByValue(CostManager.getVipFetchList(), id);
--        end
--    end
--    return nil;
--end

-----监听等级变化
--function CostManager.FreshLevelInfo()
--    local att = G.serverData["roleInfo"];
--    if att ~= nil then
--        CostManager.setPlayerBehaviorTime(Config.CostOpenCondition.AchieveLevel, att.show.level);
--    end
--end
return CostManager